//
//  EMIMHelper.swift
//  swiftim
//
//  Created by yangjian on 2023/5/30.
//

import Foundation
import RxSwift
import HyphenateChat

enum IMChatType : Int {
    case singleChat
    case groupChat
    case chatRoomChat
}


class EMIMHelper {
    static let share = EMIMHelper()
    private init(){}
    
    //处理未读消息数相关
    var currentConversationid = ""
    var unreadSubject = BehaviorSubject(value: 0)
    var unreadBag = DisposeBag()
    var localCallRecordSubject = PublishSubject<[EMChatMessage]>()

    
    
    //初始界面跳转
    var appdelegate : AppDelegate?
    var bag = DisposeBag()
    
    //当前会话通知中心
    //通话记录<>

    //发送一张名片 <username>
    var sendUserCardSubject = PublishSubject<String>()
    //用户属性有更新
    var userinfoUpdateFinishSubject = PublishSubject<[String]>()
    //聊天室更新
    var roominfoUpdateFinishSubject = PublishSubject<Void>()
    
    
    func config(appdelegate : AppDelegate){
        self.appdelegate = appdelegate
        
        bag = DisposeBag()
        
        //初始化SDK
//        EMAppConfig.share.configIMClient()
        //监听登录状态做界面路由跳转
        RXEMObservableManager.share.clientObservable.rx_loginState.subscribe { state in
            switch state {
            case .login:
                //初始化未读消息数相关组件
                print("username:\(EMClient.shared().currentUsername)")
                self.configUnreadMessageCount()
                //跳转界面
                self.jumpToRootVC()
                break
            default:
//                //释放未读消息数相关组件
//                self.releaseUnreadMessageCount()
                //跳转界面
                EMClient.shared().logout(false)
                self.jumpToLoginVC()
                break
            }
        }.disposed(by: bag)
    }
}

//初始跳转界面相关
extension EMIMHelper{
    func jumpToLoginVC(){
        self.appdelegate?.window?.rootViewController = EMLoginVC()
    }
    func jumpToRootVC(){
        self.appdelegate?.window?.rootViewController = EMRootTabBarVC()
    }
}

extension EMIMHelper{
    //处理未读消息数相关
    func configUnreadMessageCount(){
        unreadBag = DisposeBag()
        //登录成功,获取未读消息数  如果不延时,则可能获取失败.如果依然获取失败,可能需要加延时时长
        RXEMObservableManager.share.chatObservable.rx_messagesDidReceive.subscribe {[unowned self] messages in
            self.updateUnreadMessageCount()
        }.disposed(by: unreadBag)
        
        
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {[unowned self] in
            self.updateUnreadMessageCount()
        }
    }
    
//    //释放未读消息数配置
//    func releaseUnreadMessageCount(){
//        unreadBag = DisposeBag()
//        self.unreadSubject.onNext(0)
//    }
    //计算未读消息数逻辑
    func fetchUnreadCount() -> Int{
        let conversations = EMClient.shared().chatManager!.getAllConversations();
        guard let conversations else {
            return 0;
        }
//        let conversations = EMClient.shared().chatManager!.getAllConversations() as! [EMConversation]
        var count = 0
        
        let noPushUsers = EMClient.shared().pushManager?.noPushUIds as! [String]
        let noPushGroups = EMClient.shared().pushManager?.noPushGroups as! [String]
        
        for conversation in conversations {
            if noPushUsers.contains(conversation.conversationId) {continue}
            if noPushGroups.contains(conversation.conversationId) {continue}
            count += Int(conversation.unreadMessagesCount)
        }
        return count
    }
    
    //更新未读消息数
    func updateUnreadMessageCount(){
        self.unreadSubject.onNext(self.fetchUnreadCount())
    }
}

extension EMIMHelper {
    //头像相关
//    func fetchUserInfo(usernames : [String]) -> [String:EMUserInfo] {
//        
//        
//        
//        
//    }
    
}

